<template>
  <div class="allinfo" style="height:900px">
    <!-- 第一行 -->
    <div class="firstline">
      <span style="font-weight:bold;position: relative; margin-left:20px;top:15px">新增选货单</span>
      <div class="submitandcancel">
        <el-button type="primary" @click="commit()" icon="el-icon-s-promotion">提交</el-button>
        <el-button type="primary" @click="cancel()"><i class="el-icon-s-release"></i>取消</el-button>
      </div>
    </div>
    <hr>
    <!-- 基本信息栏 -->
    <div>
      <!-- 第二行 -->
      <div>
        <span class="infoborder">基本信息</span>
      </div>
      <!-- 选填信息 -->
      <div style="margin-top:20px">
        <el-form :inline="true" label-width="80px" :model="formLabelAlign">
          <el-row>
            <el-col :span="7">
              <el-form-item label="品类">
                <el-select v-model="formdata.soType" placeholder="请选择">
                  <el-option v-for="item in formLabelAlign.goodstype" :key="item.label" :label="item.name"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="7" style="margin-left:70px">
              <el-form-item label="制单人">
                <el-input v-model="formdata.createdBy" :disabled="true"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="7">
              <el-form-item label="制单时间">
                <el-input v-model="formdata.createdTime" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="7" style="margin-left:1px">
              <el-form-item label="单号">
                <el-input v-model="formdata.name" :disabled="true"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="7" style="margin-left:55px">
              <el-form-item label="客户">
                <el-select v-model="formdata.customer" placeholder="请选择">
                  <el-option v-for="item in formLabelAlign.client" :key="item.label" :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="7" style="margin-left:0px">
              <el-form-item label="成色">
                <el-select v-model="formdata.condition" placeholder="请选择">
                  <el-option v-for="item in formLabelAlign.purity" :key="item.label" :label="item.name"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="7">
              <el-form-item label="地区">
                <el-select v-model="formdata.regin" placeholder="请选择" @change="regions">
                  <el-option v-for="item in formLabelAlign.regions" :key="item.value" :label="item.name"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>


            <el-col :span="7" style="margin-left:55px">
              <el-form-item label="仓库">
                <el-select v-model="formdata.repository" placeholder="请选择">
                  <el-option v-for="item in formLabelAlign.warehouse" :key="item.label" :label="item.name"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="7" style="margin-left:0px">
              <el-form-item label="状态">
                <el-select v-model="formdata.soOperateStatus" placeholder="请选择">
                  <el-option v-for="item in formLabelAlign.status" :key="item.label" :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="7" style="margin-left:0px">
              <el-form-item label="部门">
                <el-select v-model="formdata.dept" placeholder="请选择">
                  <el-option v-for="item in formLabelAlign.department" :key="item.label" :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>

        </el-form>
      </div>
    </div>
    <!-- 产品信息栏 -->
    <div>
      <div>
        <div style="height:40px">
          <span class="infoborder">产品信息</span>
          <el-button type="primary" style="float:right" @click="table = true;find()">
            <i class="el-icon-circle-plus-outline" />添加
          </el-button>
        </div>
        <!-- 弹出框内容 -->

        <el-drawer title="选择客户的商品" :visible.sync="table" direction="ttb" size="50%" fullscreen="true">
          <el-table ref="multipleTable" :data="gridData" tooltip-effect="dark" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="" label="序号" width="120" type="index">
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" width="300">
            </el-table-column>
            <el-table-column prop="customer" label="客户">
            </el-table-column>
            <el-table-column prop="condition" label="成色" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="weight" label="重量" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="数量" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-button type="warning" circle @click="productSub(scope.row,scope.$index,scope.row.amount)">-
                </el-button>
                <span>
                  {{scope.row.amount}}
                </span>
                <el-button type="warning" @click="productAdd(scope.row,scope.$index,scope.row.amount)" circle>+
                </el-button>
              </template>

            </el-table-column>
          </el-table>
          <div style="margin-top: 20px;margin-left:800px">
            <el-button @click="insert()">确定</el-button>
            <el-button @click="table = false">取消</el-button>
          </div>
        </el-drawer>
      </div>
      <el-table :data="selectorderlist" style="width: 100%">
        <el-table-column type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column prop="productInfo" label="产品信息">
        </el-table-column>
        <el-table-column prop="productName" label="产品名称">
        </el-table-column>
        <el-table-column prop="productCode" label="条码">
        </el-table-column>
        <el-table-column prop="customer" label=" 客户">
        </el-table-column>
        <el-table-column prop="region" label="区域">
        </el-table-column>
        <el-table-column prop="condition" label="成色">
        </el-table-column>
        <el-table-column prop="weight" label="重量">
        </el-table-column>
        <el-table-column prop="amount" label="数量">
        </el-table-column>
        <el-table-column prop="perGram" label="克工费">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" icon="el-icon-delete" circle
              @click.native.prevent="deleteRow(scope.$index, selectorderlist)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="1"
        :page-sizes="[10, 20, 30]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="count">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  // 导入相依组件
  import productApi from '@/api/sale/soAccount/product'
  import soAcountApi from '@/api/sale/soAccount/soAccount'
  export default {
    data() {
      return {
        //选货单状态
        formstatus: '',

        count: 0,
        //将基础信息和产品信息同时传过去
        selectgoodsinfo: {
          basicinfo: {},
          goodsinfo: {},
        },

        // 基础信息
        formdata: {
          soType: '',
          customer: '',
          condition: '',
          repository: '',
          soOperateStatus: '',
          dept: '',
          name: this.createOrder(),
          createdBy: 'xs',
          //返回的对象
          chooseProduceMsgs: [],
          //制单时间
          createdTime: this.getTime().replace(' ', 'T'),

          weight: 0,
          amount: 0,
          regin: ''
        },
        prductNum: [],
        //选择下拉框
        formLabelAlign: {
          name: '',
          region: '',
          type: 'aaa',
          goodstype: [],
          client: [{
              label: '老王',
            },
            {
              label: '小王',
            },
            {
              label: '泰森',
            },
            {
              label: '杰克',
            },
          ],
          purity: [],
          warehouse: [],
          regions: [],
          status: [{
              label: '草稿',
              value: '1'
            },
            {
              label: '已完成',
              value: '2'
            },
          ],
          department: [{
              label: '销售部A',
            },
            {
              label: '销售部B',
            },
          ],
        },
        //产品栏展示的内容
        selectorderlist: [],
        // 添加商品信息

        table: false,
        loading: false,

        //弹出框展示的内容
        gridData: [],
        //已勾选的产品内容
        multipleSelection: [],
      }
    },
    methods: {
      regions(val) {

        let regin;
        for (const index in this.formLabelAlign.regions) {
          if (this.formLabelAlign.regions[index].value == val) {
            regin = this.formLabelAlign.regions[index];
            break
          }
        }
        let dict = JSON.parse(localStorage.getItem("dict"))
        //地区
        let warehouse;
        console.log(regin.dictCode);
        for (const index in dict) {
          if (dict[index].dictCode == regin.dictCode) {
            warehouse = index
            this.formLabelAlign.warehouse = []
            this.formdata.repository = ''
          }
          if (warehouse != -1 && dict[index].parentId == warehouse) {
            this.formLabelAlign.warehouse.push(dict[index])
          }
        }


        console.log(this.formLabelAlign.warehouse);



      },

      //提交
      commit() {
        for (const index in this.multipleSelection) {
          let chooseProduceMsg = {
            customer: this.multipleSelection[index].customer,
            nums: this.multipleSelection[index].amount,
            pid: this.multipleSelection[index].productId,
            createdBy: 'xs',
            updateBy: 'xs'
          }
          console.log(chooseProduceMsg);
          this.formdata.chooseProduceMsgs.push(chooseProduceMsg)
        }

        console.log(this.formdata);
        soAcountApi.addSoAccount(this.formdata).then(res => {
          console.log(res);
        })

        //   console.log(this.multipleSelection);
        // this.$confirm('此操作将提交本页信息, 是否继续?', '提示', {
        //     confirmButtonText: '确定',
        //     cancelButtonText: '取消',
        //     type: 'warning',
        //   })
        //   .then(() => {
        //     this.$message({
        //       type: 'success',
        //       message: '提交成功!',
        //     })
        //     var status = this.formstatus
        //     console.log(status)
        //     if (status == '草稿') {
        //       this.formdata.status = 0
        //     } else {
        //       this.formdata.status = 1
        //     }

        //     //提交选货单
        //     this.axios({
        //       method: 'post',
        //       url: this.baseUrl + 'sales/addselectorder',
        //       data: {
        //         // selectgoodsinfo:this.selectgoodsinfo
        //         SelectgoodsBasicinfo: this.formdata,
        //         selectorderlist: this.selectorderlist,
        //         // goodsinfo:this.selectorderlist
        //       },
        //     }).then((res) => {})
        //     //跳转到选货单列表页
        //     this.$router.push({
        //       path: 'selectgoodslist'
        //     })
        //   })
        //   .catch(() => {
        //     this.$message({
        //       type: 'info',
        //       message: '已取消提交',
        //     })
        //   })
      },

      //删除产品信息当前行
      deleteRow(index, rows) {
        // console.log(rows);
        // console.log(index);
        let selectProduct = rows.splice(index, 1)
        this.formdata.weight = this.formdata.weight - (selectProduct.weight * selectProduct.amount)

        console.log(selectProduct);
        var selectorderlist = this.selectorderlist
        this.count = this.selectorderlist.length
        this.formdata.amount = this.count
      },


      //取消按钮返回搜索页面
      cancel() {
        this.$router.push({
          path: 'selectgoodslist'
        })
      },

      // 对应上面的库存 + -
      productSub(row, index) {
        let num = row.amount
        num--;
        if (num >= this.prductNum[index] ||
          num < 1) {
          return
        }
        row.amount = num
      },

      productAdd(row, index) {
        let num = row.amount
        num++;
        if (row.amount >= this.prductNum[index] ||
          row.amount < 1) {
          return
        }
        row.amount = num
      },


      //将复选的产品放入产品信息栏
      insert() {
        console.log(this.$data.multipleSelection)
        let value = this.$data.multipleSelection
        for (const index in value) {
          this.selectorderlist.push(value[index])
          this.formdata.weight = this.formdata.weight + (value[index].weight * value[index].amount)
        }
        this.count = this.selectorderlist.length
        this.formdata.amount = this.count
        this.$data.table = false
        this.$message.success("添加成功")

        let selectProduct = rows.splice(index, 1)


      },
      //查询点击添加按钮之后的信息
      find() {

        productApi.findProductByPage(1, 5, {}).then(res => {
          console.log(res);
          this.gridData = res.data.list
          for (const index in this.gridData) {
            this.prductNum.push(this.gridData[index].amount)
          }

          // console.log(this.gridData);
        })
      },


      //分页
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`)
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`)
      },
      // 全选功能方法
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      //获取当前制表时间
      getTime() {
        var date1 = new Date()
        var year = date1.getFullYear()
        var month = date1.getMonth() + 1
        if (month >= 1 && month <= 9) {
          month = '0' + month
        }
        var day = date1.getDate()
        if (day >= 1 && day <= 9) {
          day = '0' + day
        }
        var hours = date1.getHours()
        if (hours >= 1 && hours <= 9) {
          hours = '0' + hours
        }
        var minutes = date1.getMinutes()
        if (minutes >= 1 && minutes <= 9) {
          minutes = '0' + minutes
        }
        var seconds = date1.getSeconds()
        if (seconds >= 1 && seconds <= 9) {
          seconds = '0' + seconds
        }
        return (
          year +
          '-' +
          month +
          '-' +
          day +
          ' ' +
          hours +
          ':' +
          minutes +
          ':' +
          seconds
        )
      },

      //生成订单号
      createOrder() {
        var date = new Date()
        var ordernum = 'XH' + date.getTime()
        console.log(date)
        return ordernum
      },
      // 获得所有分类
      initFrom() {
        let dict = JSON.parse(localStorage.getItem("dict"))
        let category;
        let condition; //"CONDITION"
        let region;


        // console.log(dict);
        for (const index in dict) {
          if (dict[index].dictCode == 'CATEGORY') {
            category = index;
            // console.log(category);
            this.formLabelAlign.goodstype = [];
          }
          if (dict[index].dictCode == 'CONDITION') {
            condition = index;
            this.formLabelAlign.purity = [];
          }

          if (dict[index].dictCode == 'REGION') {
            region = index
            console.log(region);
            this.formLabelAlign.region = []
          }
          // 品类
          if (category != -1 && dict[index].parentId == category) {
            this.formLabelAlign.goodstype.push(dict[index])
          }
          // 成色
          if (condition != -1 && dict[index].parentId == condition) {
            this.formLabelAlign.purity.push(dict[index])
          }

          //地区
          if (region != -1 && dict[index].parentId == region) {
            this.formLabelAlign.regions.push(dict[index])
          }
        }
      },


    },
    created() {
      this.initFrom()

      // var ordernum = this.$route.query.ordernum
      // console.log(ordernum)
      // if (ordernum != null) {
      //   this.axios({
      //     method: 'get',
      //     url: this.baseUrl + 'sales/getdetailbyno',
      //     params: {
      //       no: ordernum,
      //     },
      //   }).then((res) => {
      //     console.log(res.data.data)
      //     this.formdata = res.data.data
      //     this.count = res.data.data.selectgoodsGoodsinfos.length
      //     console.log(res.data.data.status)
      //     if (res.data.data.status == 0) {
      //       this.formstatus = '草稿'
      //     } else {
      //       this.formstatus = '已完成'
      //     }
      //     this.selectorderlist = res.data.data.selectgoodsGoodsinfos
      //   })
      // } else {
      //   // alert(this.$store.state.grades.account);
      //   this.formdata.documentmaker = this.$store.state.grades.account
      // }
    },
  }

</script>

<style scoped>
  .submitandcancel {
    float: right;
    margin-top: 10px;
  }

  .allinfo {
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  }

  .infoborder {
    border-style: solid;
    padding-left: 10px;
    margin-left: 10px;
    border-color: white white white skyblue;
  }

  .firstline {
    height: 50px;
  }

</style>
